package com.fingard.dsp.bank.directbank.zjtlcb02;

import net.sf.json.JSONObject;

import java.util.Date;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.IBalance;
import com.fingard.dsp.bank.directbank.zjtlcb02.util.AESCipher;
import com.fingard.dsp.bank.directbank.zjtlcb02.util.MD5Util;
import com.fingard.dsp.bank.reqrespobj.balance.Req7505HisBalQry;
import com.fingard.dsp.bank.reqrespobj.balance.Req7506BalQry;
import com.fingard.dsp.bank.reqrespobj.balance.RetAts7505HisBalQry;
import com.fingard.dsp.bank.reqrespobj.balance.RetAts7506BalQry;
import com.fingard.dsp.bank.reqrespobj.balance.detail.RetAtsBalDetail;

/**
 * Created by F on 2018/9/12.
 * 泰隆银行 余额查询
 */
public class ZJTLCB02Balance extends ZJTLCB02Base implements IBalance {

    /**
     * 查询余额
     * @param p_req7506
     * @return
     * @throws Exception
     */
    @Override
    public RetAts7506BalQry d_7506_BalQry(Req7506BalQry p_req7506) throws Exception {
        RetAts7506BalQry retAts7506BalQry = new RetAts7506BalQry(p_req7506.reqHeader);
        retAts7506BalQry.writeStart();
        try {
            while (p_req7506.readRecord()) {
                RetAtsBalDetail detail = new RetAtsBalDetail();
                String seqNo=getQryTransID();
                //报文头
                JSONObject jsonHead = new JSONObject();
                jsonHead.put("txSno",p_req7506.reqHeader.transSeqID);// 交易流水号
                jsonHead.put("mrchSno",p_req7506.reqHeader.reqSeqID);// 商户业务编号
                jsonHead.put("bussSeqNo",seqNo);// 银行业务编号
                jsonHead.put("txTime", Format.DateTimeFormat.format(new Date()));// 交易时间
                jsonHead.put("productId",""); // 产品ID
                //报文体
                JSONObject jsonBody = new JSONObject();
                jsonBody.put("sourceType","J01");//	渠道类型
                jsonBody.put("branchId",getBankConfig().getValueAsString("branchId"));//	发送方机构号
                jsonBody.put("userId",getBankConfig().getValueAsString("userId"));//	服务请求者身份
                jsonBody.put("orgSysId",getBankConfig().getValueAsString("orgSysId"));//	原始发起方系统ID
                jsonBody.put("corpCode",getBankConfig().getValueAsString("corpCode"));//	法人类型代码
                jsonBody.put("acctNo",p_req7506.readedDetail.actNum);//	账号
                jsonBody.put("clientName",bankFront.loginName);//	客户名称
                jsonBody.put("ccy",convertCurToBank(p_req7506.readedDetail.actCur));//	币种
                jsonBody.put("clientNo",bankFront.org);//	客户号
                jsonBody.put("acctName",p_req7506.readedDetail.actName);//	账户名称
                String data="<?xml version=\"1.0\" encoding=\"utf-8\"?><T><D><M><k>账号</k><v>"+p_req7506.readedDetail.actNum+"</v></M></D><E><M><k>客户号</k><v>"+bankFront.org+"</v></M></E></T>";
                jsonBody.put("signCert",ukeyData(data).trim());//	签名证书
                //报文内容
                JSONObject jsonReqData = new JSONObject();
                jsonReqData.put("head", jsonHead);
                jsonReqData.put("body", jsonBody);
                //拼接请求json串:data
                JSONObject jsonObject = new JSONObject();
                ZJTLCB02Header tlcb02Header = new ZJTLCB02Header();
                tlcb02Header.seqNO = seqNo;
                //验证开发者
                String appAccessToken=checkDeveloper(seqNo);
                tlcb02Header.appAccessToken = appAccessToken;
                //MD5加密签名串
                WriteBankLogLn("MD5加密原文:"+new StringBuilder(jsonReqData.toString()).append(seqNo).append(bankFront.keyID).toString());
                String sign= MD5Util.md5_(new StringBuilder(jsonReqData.toString()).append(seqNo).append(bankFront.keyID).toString());
                tlcb02Header.sign = sign;
                JsonHeader(jsonObject, tlcb02Header);
                jsonObject.put("reqData", jsonReqData);
                WriteBankLogLn("发送银行请求报文原文："+jsonObject.toString());
                //AES256加密
                String aesData= AESCipher.encrypt(jsonReqData.toString(), MD5Util.md5_(seqNo + appAccessToken + bankFront.keyID));
                jsonObject.put("reqData", aesData);
                //发送请求报文
                String[] bankResult = sendToBank(jsonObject.toString(),"dpstAcctQueryBCDC");
                //处理响应报文
                if (bankResult[0].length() == 0) {
                    JSONObject jsonArray = JSONObject.fromObject(bankResult[1].replaceAll(" ",""));
                    //AES256解密
                    String rspData = AESCipher.decrypt(jsonArray.get("rspData").toString(), MD5Util.md5_(seqNo + appAccessToken + bankFront.keyID));
                    jsonArray.put("rspData",rspData);
                    WriteBankLogLn("银行返回已解密的报文："+jsonArray.toString());
                    if(!"".equals(jsonArray.get("errorCode")) && jsonArray.get("errorCode")!=null){
                        if(isActiveRetCode(jsonArray.get("errorCode").toString())){
                            JSONObject jsonRspData=JSONObject.fromObject(rspData);
                            JSONObject jsonBodys=(JSONObject)jsonRspData.get("body");
                            if(!"".equals(jsonBodys) && jsonBodys!=null){
                                detail.respCode = "0";//响应码
                                detail.respInfo = "成功";//响应信息
                                detail.actCur = jsonBodys.get("ccy")!=null?convertCurToATS(jsonBodys.get("ccy").toString())
                                :convertCurToATS(getBankConfig().getMapKeyByValue("curActMapping", p_req7506.readedDetail.actNum));//币种
                                detail.actNum = jsonBodys.get("dmdAcctNo")!=null?jsonBodys.get("dmdAcctNo").toString():"";//账号
                                detail.availBal = jsonBodys.get("avlblBal")!=null?jsonBodys.get("avlblBal").toString():"";//可用余额
                                detail.currBal = jsonBodys.get("olAcctBal")!=null?jsonBodys.get("olAcctBal").toString():"";//余额
                                detail.frozenBal=jsonBodys.get("frzAmt")!=null?jsonBodys.get("frzAmt").toString():"";//冻结余额
                            }else {
                                detail.respCode = "-1";
                                detail.respInfo = "返回rspData或者body内容为空";
                            }
                        }else {
                            detail.respCode = "-1";
                            detail.respInfo = jsonArray.get("errorMsg").toString();
                        }
                    }else {
                        detail.respCode = "-1";
                        detail.respInfo = "响应码未返回";
                    }
                } else {
                    detail.respCode = "-1";
                    detail.respInfo = bankResult[1];
                }
                retAts7506BalQry.writeRetDetail(detail, p_req7506.isBatch);
            }
        }catch (Exception e){
            WriteBankLogLn("查询余额异常"+e);
            retAts7506BalQry.writeRespCode("-1");
            retAts7506BalQry.writeRespInfo(e.getMessage());
            e.printStackTrace();
        }
        retAts7506BalQry.writeEnd();
        return retAts7506BalQry;
    }

    @Override
    public RetAts7505HisBalQry d_7505_BalQry(Req7505HisBalQry p_req7505) throws Exception {
        return null;
    }
}
